<?php

namespace app\api\controller;

use app\admin\model\Member;
use app\admin\model\SysConfig;
use app\api\service\BlockChain;
use app\common\CacheKey;
use app\common\Jwt;
use think\captcha\Captcha;
use think\Db;
use think\facade\Lang;
use app\common\Status;
use app\admin\model\MemberLogs;

class Login extends Base
{

    /**
     * @Title: saveToCache
     * @Description: 写入缓存
     * @param $user_id
     * @param $user_name
     * @param $is_lock
     * @param int $type
     * @return bool|string|\think\response\Json
     */
    public function saveToCache($user_id, $user_name, $is_lock, $type = 1)
    {
        $expire_in = (int)env('REDIS.USER_TOKEN_TIMEOUT');
        $token_info = array
        (
            'uid' => $user_id,
            'name' => $user_name,
            'is_lock' => $is_lock,
            'iat' => time(),
            'exp' => time() + $expire_in,  // 默认过期时间：100小时
            'nbf' => time(),
            'sub' => env('app_domain'),
            'jti' => md5(uniqid('JWT') . time()),
        );
        $token = Jwt::getToken($token_info);
        if ($type == 1) {
            $key = sprintf(CacheKey::USER_TOKEN, $user_id);
        } else {
            $key = sprintf(CacheKey::ADMIN_TOKEN, $user_id);
        }
        $result = redis()->set($key, $token, $expire_in);
        if (!$result) {
            return returnJson(Status::SYSTEM_ERROR, Lang::get('system_error'));
        }
        return $token;
    }

    /**
     * 生成令牌
     *
     * @return string
     */
    public static function generateToken()
    {
        $randChar = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $tokenSalt = env('APP.TOKEN_SALT');
        return md5($randChar . $timestamp . $tokenSalt);
    }

    /**
     * 会员登录
     * @return \think\response\Json
     */
    public function login()
    {
        $post = $this->request->post();
        $userAddress = $post['userAddress'];
        try {
            if (!$userAddress) {
                return returnJson(Status::NAME_ERROR, Lang::get('user_address_require'));
            }
            $res = Member::getInstance()->getOne(['user_address' => $userAddress]);
            // 不存在则添加
            if (!$res) {
                $info = ['user_address' => $userAddress, 'add_time' => time(), 'updated_time' => time()];
                Member::getInstance()->insertGetId($info);
            }

            // 记录IP相关信息
            /*$info = $this->ipForCountry(get_client_ip());
            $info['ip'] = get_client_ip();
            $info['uid'] = $res['id'];
            $info['name'] = $res['name'];
            $info['device_sn'] = isset($post['deviceNo']) ? $post['deviceNo'] : "";
            $info['add_time'] = time();
            MemberLogs::getInstance()->insertGetId($info);*/

            return returnJson(Status::SUCCESS, '', []);
        } catch (\Exception $e) {
            errorLog($this->action, $e);
            return returnJson(Status::SYSTEM_ERROR, Lang::get('system_error'));
        }
    }

    /**
     * 用户恐龙数
     * @return \think\response\Json
     */
    public function userDinosaurNum()
    {
        $post = $this->request->post();
        $userAddress = $post['userAddress'];
        try {
            if (!$userAddress) {
                return returnJson(Status::NAME_ERROR, Lang::get('user_address_require'));
            }
            $where = ['user_address' => $userAddress];
            $res = Member::getInstance()->getOne($where);
            $num = (new BlockChain())->getUserDinosaurNum($userAddress);
            // 用户上级
            $superior = (new BlockChain())->getUserFather($userAddress);
            // 不存在则添加
            if (!$res) {
                $info = [
                    'user_address' => $userAddress,
                    'dinosaur_num' => $num,
                    'pid' => $superior,
                    'add_time' => time(),
                    'updated_time' => time()
                ];
                Member::getInstance()->insertGetId($info);
            } else {
                $data = ['dinosaur_num' => $num, 'pid' => $superior];
                Member::getInstance()->updateMember($where, $data);
            }

            return returnJson(Status::SUCCESS, '', []);
        } catch (\Exception $e) {
            errorLog($this->action, $e);
            return returnJson(Status::SYSTEM_ERROR, Lang::get('system_error'));
        }
    }

    /**
     * 用户金币数
     * @return \think\response\Json
     */
    public function userCoinNum()
    {
        $post = $this->request->post();
        $userAddress = $post['userAddress'];
        try {
            if (!$userAddress) {
                return returnJson(Status::NAME_ERROR, Lang::get('user_address_require'));
            }
            $where = ['user_address' => $userAddress];
            $res = Member::getInstance()->getOne($where);
            $num = (new BlockChain())->getUserCoinNum($userAddress);
            // 用户上级
            $superior = (new BlockChain())->getUserFather($userAddress);
            // 不存在则添加
            if (!$res) {
                $info = [
                    'user_address' => $userAddress,
                    'gold_coin_num' => $num,
                    'pid' => $superior,
                    'add_time' => time(),
                    'updated_time' => time()
                ];
                Member::getInstance()->insertGetId($info);
            } else {
                $data = ['gold_coin_num' => $num, 'pid' => $superior];
                Member::getInstance()->updateMember($where, $data);
            }

            return returnJson(Status::SUCCESS, '', []);
        } catch (\Exception $e) {
            errorLog($this->action, $e);
            return returnJson(Status::SYSTEM_ERROR, Lang::get('system_error'));
        }
    }

    /**
     * 用户探险次数
     * @return \think\response\Json
     */
    public function userAdventureNum()
    {
        $post = $this->request->post();
        $userAddress = $post['userAddress'];
        try {
            if (!$userAddress) {
                return returnJson(Status::NAME_ERROR, Lang::get('user_address_require'));
            }
            $where = ['user_address' => $userAddress];
            $res = Member::getInstance()->getOne($where);
            $num = (new BlockChain())->getUserAdventureNum($userAddress);
            // 用户上级
            $superior = (new BlockChain())->getUserFather($userAddress);
            // 不存在则添加
            if (!$res) {
                $info = [
                    'user_address' => $userAddress,
                    'adventure_num' => $num,
                    'pid' => $superior,
                    'add_time' => time(),
                    'updated_time' => time()];
                Member::getInstance()->insertGetId($info);
            } else {
                $data = ['adventure_num' => $num, 'pid' => $superior];
                Member::getInstance()->updateMember($where, $data);
            }

            return returnJson(Status::SUCCESS, '', []);
        } catch (\Exception $e) {
            errorLog($this->action, $e);
            return returnJson(Status::SYSTEM_ERROR, Lang::get('system_error'));
        }
    }
}
